package com.example.carrierapp.ui.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.support.v4.app.FragmentPagerAdapter
import com.example.carrierapp.base.MVPBaseActivity
import com.example.carrierapp.bean.main.VersionBean
import com.example.carrierapp.common.CarrierApplication
import com.example.carrierapp.ui.guidedialog.GuideDialog
import com.example.carrierapp.ui.main.dispatch.DispatchFragment
import com.example.carrierapp.ui.main.goodssource.FindGoodsSourceFragment
import com.example.carrierapp.ui.main.waybill.WaybillFragment
import com.example.carrierapp.ui.person.PersonCenterFragment
import com.example.carrierapp.util.AppUtil
import com.example.carrierapp.util.CheckUpUtils
import com.example.carrierapp.util.LogUtil
import com.example.carrierapp.util.ToastUtils
import com.example.lb.fingerdemo.R
import kotlinx.android.synthetic.main.activity_main.*
import pub.devrel.easypermissions.EasyPermissions

open class MainActivity : MVPBaseActivity<MainContract.View, MainPresenter>(), MainContract.View {
    private val mFragments by lazy {
        arrayListOf(FindGoodsSourceFragment.newInstance(),
                DispatchFragment.newInstance(),
                WaybillFragment.newInstance(),
                PersonCenterFragment.newInstance())
    }
    private var mVersionBean: VersionBean? = null
    private var mHaveInstallPermission: Boolean = false
    private var guideDialog: GuideDialog? = null

    override fun getContentView(): Int {
        return R.layout.activity_main
    }

    override fun getTitleString(): String {
        return "承运宝"
    }

    override fun createPresenter(): MainPresenter {
        return MainPresenter(this)
    }

    override fun initData() {
        checkPermission()
        mPresenter.attachView(this)
        mPresenter.checkUpdate()
        pager.offscreenPageLimit = 4
        pager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
            override fun getItem(position: Int) = mFragments[position]

            override fun getCount() = mFragments.size
        }
    }

    override fun initEvent() {
        showGuide(0)
        tab.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.goodssource -> {
                    pager.currentItem = 0
                }
                R.id.dispatch -> {
                    pager.currentItem = 1
                    showGuide(1)
                }

                R.id.waybill -> {
                    pager.currentItem = 2
                    showGuide(2)
                }
                R.id.mine -> pager.currentItem = 3
            }
            true
        }
    }

    private fun checkPermission() {
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            EasyPermissions.requestPermissions(
                    this,
                    "请打开写入文件权限！",
                    100,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        mHaveInstallPermission = false
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mHaveInstallPermission = packageManager.canRequestPackageInstalls()
            if (!mHaveInstallPermission) { //权限没有打开则提示用户去手动打开
                ToastUtils.showCenterToast(this, "需要打开允许来自此来源，请去设置中开启此权限")
                val packageURI = Uri.parse("package:$packageName")
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                startActivityForResult(intent, 0x01)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
        if (requestCode == 0x01 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            LogUtil.i("有更新")
            mVersionBean?.let {
                it.versionCode > AppUtil.getVerCode(this)
                CheckUpUtils.showNoticeDialog(this, it.filePath, it.isUpdate, it.remark)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0x01 && resultCode == RESULT_OK)
            mHaveInstallPermission = true
    }

    override fun checkUpdateSuccess(bean: VersionBean?) {
        mVersionBean = bean
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            EasyPermissions.requestPermissions(
                    this,
                    "请打开写入文件权限！",
                    100,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
        } else if (bean != null) {
            if (bean.versionCode > AppUtil.getVerCode(CarrierApplication.mAppContext)) {//有更新
                LogUtil.i("有更新")
                CheckUpUtils.showNoticeDialog(this, bean.filePath, bean.isUpdate, bean.remark)
            }
        }
    }

    private fun showGuide(position: Int) {
        if (guideDialog == null) {
            guideDialog = GuideDialog(this).apply {
                setOnDismissListener {
                    if (position == 1)
                        sendBroadcast(Intent("guide_end"))
                }
            }
        }
        guideDialog?.show(position)
    }

    override fun checkUpdateFailde(msg: String?) {
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }

}
